const app = getApp()


const {
  updateUserBaseInfo
} = require('../../../api/user-center-api')
const {
  getNewUserInfo,
} = require('../../../api/common.api')

Page({
  data: {
    avatarUrl: '',
    nickname: ''
  },
  onLoad() {
    let _this = this;
    getNewUserInfo().then(res => {
      _this.setData({
        avatarUrl: res.avatar,
        nickname: res.nickname
      })
    })
  },
  onChooseAvatar(e) {
    const {
      avatarUrl
    } = e.detail
    let _this = this,
      access_token = '';

    try {
      var userInfo = wx.getStorageSync('userInfo')
      if (userInfo) {
        access_token = userInfo.access_token;
        wx.uploadFile({
          filePath: avatarUrl,
          name: 'file',
          header: {
            'content-type': 'application/json; charset=utf-8',
            'token': access_token
          },
          url: 'https://cebei-api.nmhywl.cn/api/upload-image',
          success(res) {

            let result = JSON.parse(res.data);
            if (result.code == 0) {
              _this.setData({
                avatarUrl: result.data.path
              })
            } else {
              wx.showToast({
                title: result.message,
                duration: 1500,
                icon: 'none'
              })
            }
            // return  
            // console.log()
          },
          fail(error) {
            wx.showToast({
              title: error,
              icon: 'none'
            })
          }
        })
      }
    } catch (e) {
      console.log('request.js中读取用户信息失败');
    }

  },
  onNicknameInput(e) {
    let _this = this;
    _this.setData({
      nickname: e.detail.value
    })
  },
  onSumit() {
    let _this = this;

    let params = {
      nickname: _this.data.nickname,
      avatar: _this.data.avatarUrl
    }
    console.log(params)
    updateUserBaseInfo(params).then( res => {
      wx.switchTab({
        url: '../index',
      })
    })
  }
})